<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold text-gray-900">车辆管理</h1>
        <p class="text-gray-600 mt-1">管理所有车辆信息和状态</p>
      </div>
      <el-button type="primary" :icon="Plus" @click="showAddDialog = true">
        添加车辆
      </el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card>
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <el-input
          v-model="searchQuery"
          placeholder="搜索车牌号、品牌或型号"
          :prefix-icon="Search"
          clearable
        />
        <el-select v-model="statusFilter" placeholder="车辆状态" clearable>
          <el-option label="空闲" value="available" />
          <el-option label="使用中" value="in_use" />
          <el-option label="维护中" value="maintenance" />
        </el-select>
        <el-select v-model="brandFilter" placeholder="品牌" clearable>
          <el-option label="丰田" value="丰田" />
          <el-option label="本田" value="本田" />
          <el-option label="大众" value="大众" />
          <el-option label="奔驰" value="奔驰" />
          <el-option label="宝马" value="宝马" />
        </el-select>
        <el-button @click="resetFilters">重置筛选</el-button>
      </div>
    </el-card>
    
    <!-- 车辆列表 -->
    <el-card>
      <el-table :data="filteredVehicles" stripe style="width: 100%">
        <el-table-column prop="licensePlate" label="车牌号" width="120" />
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="model" label="型号" width="120" />
        <el-table-column prop="color" label="颜色" width="80" />
        <el-table-column prop="year" label="年份" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="mileage" label="里程(km)" width="100" />
        <el-table-column prop="lastMaintenance" label="上次保养" width="120" />
        <el-table-column prop="currentDriver" label="当前驾驶员" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewVehicle(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editVehicle(row)">编辑</el-button>
            <el-dropdown @command="handleCommand">
              <el-button size="small" type="info">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'maintenance', vehicle: row }">
                    维护记录
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'history', vehicle: row }">
                    使用历史
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'delete', vehicle: row }" divided>
                    删除车辆
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="vehicles.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑车辆对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingVehicle ? '编辑车辆' : '添加车辆'"
      width="600px"
    >
      <el-form
        ref="vehicleFormRef"
        :model="vehicleForm"
        :rules="vehicleRules"
        label-width="100px"
      >
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <el-form-item label="车牌号" prop="licensePlate">
            <el-input v-model="vehicleForm.licensePlate" placeholder="请输入车牌号" />
          </el-form-item>
          <el-form-item label="品牌" prop="brand">
            <el-select v-model="vehicleForm.brand" placeholder="选择品牌" class="w-full">
              <el-option label="丰田" value="丰田" />
              <el-option label="本田" value="本田" />
              <el-option label="大众" value="大众" />
              <el-option label="奔驰" value="奔驰" />
              <el-option label="宝马" value="宝马" />
            </el-select>
          </el-form-item>
          <el-form-item label="型号" prop="model">
            <el-input v-model="vehicleForm.model" placeholder="请输入型号" />
          </el-form-item>
          <el-form-item label="颜色" prop="color">
            <el-input v-model="vehicleForm.color" placeholder="请输入颜色" />
          </el-form-item>
          <el-form-item label="年份" prop="year">
            <el-input-number v-model="vehicleForm.year" :min="1990" :max="2024" class="w-full" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="vehicleForm.status" placeholder="选择状态" class="w-full">
              <el-option label="空闲" value="available" />
              <el-option label="使用中" value="in_use" />
              <el-option label="维护中" value="maintenance" />
            </el-select>
          </el-form-item>
          <el-form-item label="里程(km)" prop="mileage">
            <el-input-number v-model="vehicleForm.mileage" :min="0" class="w-full" />
          </el-form-item>
          <el-form-item label="购买日期" prop="purchaseDate">
            <el-date-picker
              v-model="vehicleForm.purchaseDate"
              type="date"
              placeholder="选择购买日期"
              class="w-full"
            />
          </el-form-item>
        </div>
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="vehicleForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="saveVehicle">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 车辆详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="车辆详情" width="800px">
      <div v-if="selectedVehicle" class="space-y-4">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="space-y-3">
            <h3 class="text-lg font-medium text-gray-900">基本信息</h3>
            <div class="bg-gray-50 p-4 rounded-lg space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">车牌号:</span>
                <span class="font-medium">{{ selectedVehicle.licensePlate }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">品牌:</span>
                <span class="font-medium">{{ selectedVehicle.brand }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">型号:</span>
                <span class="font-medium">{{ selectedVehicle.model }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">颜色:</span>
                <span class="font-medium">{{ selectedVehicle.color }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">年份:</span>
                <span class="font-medium">{{ selectedVehicle.year }}</span>
              </div>
            </div>
          </div>
          <div class="space-y-3">
            <h3 class="text-lg font-medium text-gray-900">状态信息</h3>
            <div class="bg-gray-50 p-4 rounded-lg space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">当前状态:</span>
                <el-tag :type="getStatusType(selectedVehicle.status)" size="small">
                  {{ getStatusText(selectedVehicle.status) }}
                </el-tag>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">里程:</span>
                <span class="font-medium">{{ selectedVehicle.mileage }} km</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">上次保养:</span>
                <span class="font-medium">{{ selectedVehicle.lastMaintenance }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">当前驾驶员:</span>
                <span class="font-medium">{{ selectedVehicle.currentDriver || '无' }}</span>
              </div>
            </div>
          </div>
        </div>
        <div v-if="selectedVehicle.notes">
          <h3 class="text-lg font-medium text-gray-900 mb-2">备注</h3>
          <div class="bg-gray-50 p-4 rounded-lg">
            <p class="text-gray-700">{{ selectedVehicle.notes }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, ArrowDown } from '@element-plus/icons-vue'

// 接口定义
interface Vehicle {
  id: number
  licensePlate: string
  brand: string
  model: string
  color: string
  year: number
  status: 'available' | 'in_use' | 'maintenance'
  mileage: number
  lastMaintenance?: string
  currentDriver?: string
  purchaseDate?: string
  notes?: string
}

// 响应式数据
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const editingVehicle = ref<Vehicle | null>(null)
const selectedVehicle = ref<Vehicle | null>(null)
const searchQuery = ref('')
const statusFilter = ref('')
const brandFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 车辆表单
const vehicleForm = reactive({
  licensePlate: '',
  brand: '',
  model: '',
  color: '',
  year: new Date().getFullYear(),
  status: 'available' as Vehicle['status'],
  mileage: 0,
  purchaseDate: '',
  notes: ''
})

// 表单验证规则
const vehicleRules = {
  licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
  brand: [{ required: true, message: '请选择品牌', trigger: 'change' }],
  model: [{ required: true, message: '请输入型号', trigger: 'blur' }],
  color: [{ required: true, message: '请输入颜色', trigger: 'blur' }],
  year: [{ required: true, message: '请输入年份', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 模拟车辆数据
const vehicles = ref<Vehicle[]>([
  {
    id: 1,
    licensePlate: '京A12345',
    brand: '丰田',
    model: '凯美瑞',
    color: '白色',
    year: 2022,
    status: 'available',
    mileage: 15000,
    lastMaintenance: '2024-01-15',
    currentDriver: '',
    notes: '车况良好'
  },
  {
    id: 2,
    licensePlate: '京B67890',
    brand: '本田',
    model: '雅阁',
    color: '黑色',
    year: 2021,
    status: 'in_use',
    mileage: 28000,
    lastMaintenance: '2024-01-10',
    currentDriver: '张师傅',
    notes: '定期保养'
  },
  {
    id: 3,
    licensePlate: '京C11111',
    brand: '大众',
    model: '帕萨特',
    color: '银色',
    year: 2020,
    status: 'maintenance',
    mileage: 45000,
    lastMaintenance: '2024-01-20',
    currentDriver: '',
    notes: '正在进行年检'
  }
])

// 计算属性
const filteredVehicles = computed(() => {
  let filtered = vehicles.value
  
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(vehicle => 
      vehicle.licensePlate.toLowerCase().includes(query) ||
      vehicle.brand.toLowerCase().includes(query) ||
      vehicle.model.toLowerCase().includes(query)
    )
  }
  
  if (statusFilter.value) {
    filtered = filtered.filter(vehicle => vehicle.status === statusFilter.value)
  }
  
  if (brandFilter.value) {
    filtered = filtered.filter(vehicle => vehicle.brand === brandFilter.value)
  }
  
  return filtered
})

// 方法
const getStatusType = (status: Vehicle['status']) => {
  const types = {
    available: 'success',
    in_use: 'warning',
    maintenance: 'danger'
  }
  return types[status]
}

const getStatusText = (status: Vehicle['status']) => {
  const texts = {
    available: '空闲',
    in_use: '使用中',
    maintenance: '维护中'
  }
  return texts[status]
}

const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  brandFilter.value = ''
  ElMessage.success('筛选条件已重置')
}

const viewVehicle = (vehicle: Vehicle) => {
  selectedVehicle.value = vehicle
  showDetailDialog.value = true
}

const editVehicle = (vehicle: Vehicle) => {
  editingVehicle.value = vehicle
  Object.assign(vehicleForm, vehicle)
  showAddDialog.value = true
}

const handleCommand = (command: { action: string; vehicle: Vehicle }) => {
  const { action, vehicle } = command
  
  switch (action) {
    case 'maintenance':
      ElMessage.info(`查看 ${vehicle.licensePlate} 的维护记录`)
      break
    case 'history':
      ElMessage.info(`查看 ${vehicle.licensePlate} 的使用历史`)
      break
    case 'delete':
      ElMessageBox.confirm(
        `确定要删除车辆 ${vehicle.licensePlate} 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        const index = vehicles.value.findIndex(v => v.id === vehicle.id)
        if (index > -1) {
          vehicles.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      })
      break
  }
}

const saveVehicle = () => {
  if (editingVehicle.value) {
    // 编辑现有车辆
    const index = vehicles.value.findIndex(v => v.id === editingVehicle.value!.id)
    if (index > -1) {
      vehicles.value[index] = { ...editingVehicle.value, ...vehicleForm }
      ElMessage.success('车辆信息更新成功')
    }
  } else {
    // 添加新车辆
    const newVehicle: Vehicle = {
      id: Date.now(),
      ...vehicleForm
    }
    vehicles.value.push(newVehicle)
    ElMessage.success('车辆添加成功')
  }
  
  cancelEdit()
}

const cancelEdit = () => {
  showAddDialog.value = false
  editingVehicle.value = null
  Object.assign(vehicleForm, {
    licensePlate: '',
    brand: '',
    model: '',
    color: '',
    year: new Date().getFullYear(),
    status: 'available',
    mileage: 0,
    purchaseDate: '',
    notes: ''
  })
}

// 组件挂载时加载数据
onMounted(() => {
  // 这里可以调用API加载实际数据
})
</script>

<style scoped>
.el-card {
  border-radius: 8px;
}

.el-table {
  border-radius: 8px;
}
</style>